package com.qms.qep.service.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.qms.common.core.domain.AjaxResult;
import com.qms.common.utils.DateUtils;
import com.qms.common.utils.StringUtils;
import com.qms.common.utils.file.FileUtils;
import com.qms.qep.domain.Certificate;
import com.qms.qep.domain.CertificateData;
import com.qms.qep.domain.CertificateTemplate;
import com.qms.qep.mapper.CertificateMapper;
import com.qms.qep.mapper.CertificateDataMapper;
import com.qms.qep.mapper.CertificateTemplateMapper;
import com.qms.qep.service.ICertificateService;
import com.qms.qep.vo.PrintHistoryVO;

/**
 * 证书服务实现
 */
@Service
public class CertificateServiceImpl implements ICertificateService {
    
    @Autowired
    private CertificateMapper certificateMapper;
    
    @Autowired
    private CertificateDataMapper certificateDataMapper;
    
    @Autowired
    private CertificateTemplateMapper templateMapper;
    
    @Value("${qms.certificate.output-path:/certificate/output/}")
    private String outputPath;

    /**
     * 查询证书列表
     */
    @Override
    public List<Certificate> selectCertificateList(Certificate certificate) {
        return certificateMapper.selectCertificateList(certificate);
    }

    /**
     * 查询证书详细信息
     */
    @Override
    public Certificate selectCertificateById(Long id) {
        return certificateMapper.selectCertificateById(id);
    }

    /**
     * 新增证书
     */
    @Override
    public int insertCertificate(Certificate certificate) {
        certificate.setCreateTime(DateUtils.getNowDate());
        // 设置默认值
        if (StringUtils.isEmpty(certificate.getCertificateStatus())) {
            certificate.setCertificateStatus("未签发");
        }
        if (StringUtils.isEmpty(certificate.getDelFlag())) {
            certificate.setDelFlag("0");
        }
        return certificateMapper.insertCertificate(certificate);
    }

    /**
     * 修改证书
     */
    @Override
    public int updateCertificate(Certificate certificate) {
        certificate.setUpdateTime(DateUtils.getNowDate());
        return certificateMapper.updateCertificate(certificate);
    }

    /**
     * 批量删除证书
     */
    @Override
    @Transactional
    public int deleteCertificateByIds(Long[] ids) {
        // 删除关联的证书数据
        for (Long id : ids) {
            certificateDataMapper.deleteCertificateDataByCertificateId(id);
        }
        return certificateMapper.deleteCertificateByIds(ids);
    }
    
    /**
     * 下载证书
     */
    @Override
    public AjaxResult downloadCertificate(Long id) {
        Certificate certificate = certificateMapper.selectCertificateById(id);
        if (certificate == null) {
            return AjaxResult.error("证书不存在");
        }
        
        // 此处需要实现实际的文件生成或获取逻辑
        // 作为示例，直接返回证书内容
        return AjaxResult.success("下载成功", certificate.getContent());
    }
    
    /**
     * 签发证书
     */
    @Override
    @Transactional
    public int issueCertificate(Long id, Certificate certificate) {
        Certificate existCert = certificateMapper.selectCertificateById(id);
        if (existCert == null) {
            return 0;
        }
        
        // 更新签发信息
        Certificate updateCert = new Certificate();
        updateCert.setId(id);
        updateCert.setIssueDate(certificate.getIssueDate() != null ? certificate.getIssueDate() : new Date());
        updateCert.setIssuer(certificate.getIssuer());
        updateCert.setCertificateStatus("有效");
        updateCert.setUpdateTime(DateUtils.getNowDate());
        
        return certificateMapper.updateCertificate(updateCert);
    }
    
    /**
     * 作废证书
     */
    @Override
    @Transactional
    public int voidCertificate(Long id, String voidReason) {
        Certificate certificate = new Certificate();
        certificate.setId(id);
        certificate.setCertificateStatus("已作废");
        certificate.setVoidReason(voidReason);
        certificate.setUpdateTime(DateUtils.getNowDate());
        
        return certificateMapper.updateCertificate(certificate);
    }
    
    /**
     * 生成证书
     */
    @Override
    @Transactional
    public AjaxResult generateCertificate(Certificate certificate) {
        // 查询模板
        CertificateTemplate template = templateMapper.selectCertificateTemplateById(certificate.getTemplateId());
        if (template == null) {
            return AjaxResult.error("证书模板不存在");
        }
        
        // 设置模板名称
        certificate.setTemplateName(template.getName());
        
        // 生成证书编号（示例，实际应根据业务规则生成）
        if (StringUtils.isEmpty(certificate.getCertificateNo())) {
            String certificateNo = "CERT-" + DateUtils.dateTimeNow() + "-" + UUID.randomUUID().toString().substring(0, 8);
            certificate.setCertificateNo(certificateNo);
        }
        
        // 设置证书状态
        certificate.setCertificateStatus("未签发");
        certificate.setDelFlag("0");
        certificate.setCreateTime(DateUtils.getNowDate());
        
        // 保存证书信息
        certificateMapper.insertCertificate(certificate);
        
        return AjaxResult.success("证书生成成功", certificate);
    }
    
    /**
     * 查询证书数据
     */
    @Override
    public List<CertificateData> selectCertificateDataByCertificateId(Long certificateId) {
        return certificateDataMapper.selectCertificateDataByCertificateId(certificateId);
    }
    
    /**
     * 保存证书数据
     */
    @Override
    @Transactional
    public int saveCertificateData(List<CertificateData> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            return 0;
        }
        
        int rows = 0;
        for (CertificateData data : dataList) {
            if (data.getId() != null) {
                // 更新现有数据
                data.setUpdateTime(DateUtils.getNowDate());
                rows += certificateDataMapper.updateCertificateData(data);
            } else {
                // 新增数据
                data.setCreateTime(DateUtils.getNowDate());
                rows += certificateDataMapper.insertCertificateData(data);
            }
        }
        return rows;
    }
    
    /**
     * 获取输出目录
     */
    private String getOutputDir() {
        return outputPath.endsWith("/") ? outputPath : outputPath + "/";
    }
} 